# -*- python -*-
# ex: set syntax=python:

import os

#######

# This is a sample buildmaster config file. It must be installed as
# 'master.cfg' in your buildmaster's base directory.

# This is the dictionary that the buildmaster pays attention to. We also use
# a shorter alias to save typing.
c = BuildmasterConfig = {}

####### BUILDSLAVES

# The 'slaves' list defines the set of recognized buildslaves. Each element is
# a BuildSlave object, specifying a unique slave name and password.  The same
# slave name and password must be configured on the slave.
from buildbot.buildslave import BuildSlave
c['slaves'] = [
    BuildSlave("ubuntu_lucid_x86_64", os.environ['BUILDBOT_SLAVES_PASSWORD']),
    BuildSlave("win61_x86_vc9", os.environ['BUILDBOT_SLAVES_PASSWORD'])
]

# 'slavePortnum' defines the TCP port to listen on for connections from slaves.
# This must match the value configured into the buildslaves (with their
# --master option)
c['slavePortnum'] = int(os.environ['PORT_SLAVES'])

####### CHANGESOURCES

# the 'change_source' setting tells the buildmaster how it should find out
# about source code changes.  Here we point to the buildbot clone of pyflakes.

#from buildbot.changes.gitpoller import GitPoller
#c['change_source'] = GitPoller(
#       'git://github.com/buildbot/pyflakes.git',
#       workdir='gitpoller-workdir', branch='master',
#       pollinterval=300)

####### SCHEDULERS

# Configure the Schedulers, which decide how to react to incoming changes.  In this
# case, just kick off a 'runtests' build

from buildbot.schedulers.basic import SingleBranchScheduler
from buildbot.schedulers import timed
from buildbot.changes import filter
c['schedulers'] = []
c['schedulers'].append(SingleBranchScheduler(
                            name="all",
                            change_filter=filter.ChangeFilter(branch='default'),
                            treeStableTimer=None,
                            builderNames=['{0}_inc'.format(s.slavename) for s in c['slaves']]))
c['schedulers'].append(timed.Nightly(
                            name="nightly",
                            branch='default',
                            builderNames=['{0}_full'.format(s.slavename) for s in c['slaves']],
                            hour=8,minute=30))

####### BUILDERS

# The 'builders' list defines the Builders, which tell Buildbot how to perform a build:
# what steps, and which slaves can execute them.  Note that any particular build will
# only take place on one slave.

from buildbot.process.factory import BuildFactory
from buildbot.steps.source.mercurial import Mercurial
from buildbot.steps.shell import ShellCommand, Configure, Compile, Test

def create_build_factory(incremental=True):
    build_factory = BuildFactory()
    if incremental:
        build_factory.addStep(Mercurial(repourl='https://code.google.com/p/rathaxes', method='clean', branchType='inrepo', logEnviron=False))
    else:
        build_factory.addStep(Mercurial(repourl='https://code.google.com/p/rathaxes', method='fresh', branchType='inrepo', logEnviron=False))
        # method='fresh' should trigger an hg purge --all but that doesn't seem
        # to work, so let's delete the build dir manually:
        build_factory.addStep(ShellCommand(command=['cmake', '-E', 'remove_directory', 'build'], lazylogfiles=True, logEnviron=False))
    build_factory.addStep(ShellCommand(command=['cmake', '-E', 'make_directory', 'build'], lazylogfiles=True, logEnviron=False))
    # The default is already build/ thus build/build
    build_factory.addStep(Configure(command=['cmake', '-DWITH_DOCUMENTATION=1', '-DCMAKE_BUILD_TYPE=RELEASE', '..'], workdir='build/build', logEnviron=False))
    # cmake --build will invoke the correct tool for the current platform (make or nmake).
    build_factory.addStep(Compile(command=['cmake', '--build', '.'], workdir='build/build', logEnviron=False, suppressionFile='maintainers/buildbot/master/warnings.supp'))
    build_factory.addStep(Test(command=['cmake', '--build', '.', '--target', 'test'], workdir='build/build', logEnviron=False, env={'CTEST_OUTPUT_ON_FAILURE': '1'}))
    return build_factory

from buildbot.config import BuilderConfig

c['builders'] = []
for slave in c['slaves']:
    c['builders'].append(
        BuilderConfig(name='{0}_{1}'.format(slave.slavename, 'inc'),
            slavenames=[slave.slavename],
            factory=create_build_factory()))
    c['builders'].append(
        BuilderConfig(name='{0}_{1}'.format(slave.slavename, 'full'),
            slavenames=[slave.slavename],
            factory=create_build_factory(incremental=False)))

####### STATUS TARGETS

# 'status' is a list of Status Targets. The results of each build will be
# pushed to these targets. buildbot/status/*.py has a variety to choose from,
# including web pages, email senders, and IRC bots.

c['status'] = []

from buildbot.status import html
from buildbot.status.web import authz

c['status'].append(
    html.WebStatus(
        http_port=int(os.environ['PORT_WEBHOOK']),
        allowForce=True,
        change_hook_dialects={'googlecode': {'secret_key': os.environ['BUILDBOT_GOOGLE_CODE_SECRET_KEY']}}
    )
)

authz_cfg=authz.Authz(
    # change any of these to True to enable; see the manual for more
    # options
    gracefulShutdown = False,
    forceBuild = False, # use this to test your slave once it is set up
    forceAllBuilds = False,
    pingBuilder = False,
    stopBuild = False,
    stopAllBuilds = False,
    cancelPendingBuild = False,
)
c['status'].append(
    html.WebStatus(
        http_port=int(os.environ['PORT_WWW']),
        authz=authz_cfg
    )
)

from buildbot.status import words

c['status'].append(
    words.IRC('chat.freenode.net', 'ratata',
        channels=[{'channel': '#rathaxes'}],
        notify_events={
            'exception': 1,
            'successToFailure': 1,
            'failureToSuccess': 1
        },
        allowForce=True
    )
)

####### PROJECT IDENTITY

# the 'title' string will appear at the top of this buildbot
# installation's html.WebStatus home page (linked to the
# 'titleURL') and is embedded in the title of the waterfall HTML page.

c['title'] = "Rathaxes"
c['titleURL'] = "http://www.rathaxes.org/"

# the 'buildbotURL' string should point to the location where the buildbot's
# internal web server (usually the html.WebStatus page) is visible. This
# typically uses the port number set in the Waterfall 'status' entry, but
# with an externally-visible host name which the buildbot cannot figure out
# without some help.

c['buildbotURL'] = "http://builds.rathaxes.org/"

####### DB URL

# This specifies what database buildbot uses to store change and scheduler
# state.  You can leave this at its default for all but the largest
# installations.
c['db_url'] = 'postgresql+psycopg2://{user}:{password}@{host}:{port}/{db}'.format(
    user=os.environ['DOTCLOUD_DB_SQL_LOGIN'],
    password=os.environ['DOTCLOUD_DB_SQL_PASSWORD'],
    host=os.environ['DOTCLOUD_DB_SQL_HOST'],
    port=os.environ['DOTCLOUD_DB_SQL_PORT'],
    db='template1'
)
